function getSiteCfg() {
    $.getJSON(
        "/api/ocie/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.ocie_poc_email + '">' + json.ocie_poc_name +
                      '</a> ' + 'Phone: (' +
                      json.ocie_poc_phone.substr(0,3) + ') ' +
                      json.ocie_poc_phone.substr(3,3) + '-' +
                      json.ocie_poc_phone.substr(6,4);
            $("span.POCemail").append(val);
        }
    );
    $.ajax({
        type: "GET",
        url: "/api/ocie/role_check/",
        success: function(string){
            $("a.logout:contains(Options)").css("display","block");
        },
        error: function(string){
            window.location = "/ocie/";
        }
    });
}


function getUnitsInfo(unit_id) {
    var ret = undefined;
    var url = "/api/ocie/config/lists/units/";
    url += ( unit_id ) ? unit_id + "/" : "";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
	async: false,
        success: function(json){
            ret = json;
        }
    });
    return ret;
}


var putAddUnit = function() {
    $("#button_save_add_unit").parents("p").next()
        .children("*.waitMessage").show();
    var type = "PUT";
    var url = "/api/ocie/config/lists/units/";
    var data = {};
    data['description'] =
        $(":input[name=unit_name]").val();
    data['active'] =
        $(":radio:checked[name=unit_status]").val();
    var cb_success = function() {
	    buildContainers();
	}
    var cb_error = function(string) {
            $("#button_save_add_unit").parents("p").next()
                .children("*.waitMessage").hide();
            if ( string.status == "409" ){
                $("#button_save_add_unit").parents("p").next()
                    .children("*.generalErrorMessage:eq(1)").show();
            }else{
                $("#button_save_add_unit").parents("p").next()
                    .children("*.generalErrorMessage:eq(2)").show();
            }
	    bindButtons();
	}
    return formSubmit(type, url, data, cb_success, cb_error);
}


var postEditUnit = function(unit_id) {
    $("#button_save_edit_unit").parents("p").next()
        .children("*.waitMessage").show();
    var type = "POST";
    var url = "/api/ocie/config/lists/units/" + unit_id + "/";
    var data = {};
    data['description'] =
        $(":input[name=unit_name]").val();
    data['active'] =
        $(":radio:checked[name=unit_status]").val();
    var cb_success = function() {
	    buildContainers();
	}
    var cb_error = function(string) {
            $("#button_save_edit_unit").parents("p").next()
                .children("*.waitMessage").hide();
            if ( string.status == "409" ){
                $("#button_save_edit_unit").parents("p").next()
                    .children("*.generalErrorMessage:eq(1)").show();
            }else{
                $("#button_save_edit_unit").parents("p").next()
                    .children("*.generalErrorMessage:eq(2)").show();
            }
	    bindButtons(unit_id);
	}
    return formSubmit(type, url, data, cb_success, cb_error);
}


function formSubmit(type, url, data, cb_success, cb_error) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        success: cb_success,
        error: cb_error
    });
}


function buildContainers() {
    $("div.mainContent table tbody:nth-child(1) tr:nth-child(2) td")
        .html('')
        .append( proto_html['unit_list'] )
        .append( proto_html['unit_ml'] );
    showUnits();
    $("div.mainContent a.headerToggle").click( function(){
        toggleSection( this );
        return false;
    });
}


function showUnits() {
    var span = "div.mainContent table tbody:nth-child(1) " + 
               "fieldset:nth-child(1) span";
    $(span).html('')
    var json = getUnitsInfo();
    jQuery.each(json, function() {
        var desc = '<a href="#">' + this.description + '</a>';
        desc += ( this.active ) ? '<br />' : ' (Inactive)<br />';
        $(span).append(desc);
        var unit_id = this.unit_id;
        $(span + " a:last").click( function(){
            editUnit(unit_id);
            return false;
        });
    });
    bindButtons();
}


function addUnit() {
    var span = "div.mainContent table tbody:nth-child(1) tr:nth-child(2) " +
               "fieldset:nth-child(2)";
    $(span).replaceWith( proto_html['unit_ml_add'] )
    bindButtons();
}


function editUnit(unit_id) {
    var json = getUnitsInfo(unit_id);
    var span = "div.mainContent table tbody:nth-child(1) tr:nth-child(2) " +
               "fieldset:nth-child(2)";
    $(span).replaceWith( proto_html['unit_ml_edit'] )
    $(":input[name=unit_name]").val( json.description );
    if ( json.active ){
        $(":radio[name=unit_status][value=1]").attr("checked","checked");
    }else{
        $(":radio[name=unit_status][value=0]").attr("checked","checked");
    }
    bindButtons(unit_id);
}


function toggleSection(a) {
    var test =
        $(a).children("img:first[src$='collapse.gif']").length;
    var src = $(a).children("img:first").attr("src");
    src = ( test ) 
        ? src.replace(/collapse.gif/i,"expand.gif")
	: src.replace(/expand.gif/i,"collapse.gif");
    $(a).children("img:first").attr("src", src);
    if ( test ){
        $(a).parents("tr").next().hide();
        $(a).parents("td").removeClass('tableActiveColor');
    }else{
        $(a).parents("tr").next().show();
        $(a).parents("td").addClass('tableActiveColor');
    }
}


function bindButtons(unit_id) {
    $("div.mainContent a.button").unbind();
    $("#button_add_unit:not(.buttonInactive)").click( function(){
        $(this).addClass('buttonInactive');
        addUnit();
        return false;
    });
    $("#button_save_add_unit:not(.buttonInactive)").click( function(){
        if ( validateForm() ){
            $(this).unbind();
            $(this).siblings().unbind();
            $(this).parents("p").next()
                .children("*.waitMessage, *.generalErrorMessage").hide();
            putAddUnit();
        }    
        return false;
    });
    $("#button_save_edit_unit:not(.buttonInactive)").click( function(){
        if ( validateForm() ){
            $(this).unbind();
            $(this).siblings().unbind();
            $(this).parents("p").next()
                .children("*.waitMessage, *.generalErrorMessage").hide();
            postEditUnit(unit_id);
        }    
        return false;
    });
    $("#button_cancel_add_unit:not(.buttonInactive)").click( function(){
        $(this).unbind();
        buildContainers()
        return false;
    });
    $("#button_cancel_edit_unit:not(.buttonInactive)").click( function(){
        $(this).unbind();
        buildContainers()
        return false;
    });
    $("a.buttonInactive").click( function(){
        return false;
    });
}


function validateForm() {
    $("*.generalErrorMessage").hide();
    var val = $(":input[name=unit_name]").val();
    val = val.replace(/ /g, "");
    if ( val.length == 0 ){
        $("#button_save_add_unit, #button_save_edit_unit").parents("p").next()
            .children("*.generalErrorMessage:eq(0)").show();
        return false;
    }
    return true;
}


function setProtoHTML() {
    var proto_pre = {
        'unit_list':'protoCurrentUnitListHTML',
        'unit_ml':'protoManageListHTML',
        'unit_ml_add':'protoManageListAddUnitHTML',
        'unit_ml_edit':'protoManageListEditUnitHTML'
    };
    proto_html = {};
    jQuery.each(proto_pre, function(i, val) {
        proto_html[i] = $("#" + val).html();
        $("#" + val).remove();
    });
}


jQuery(function($) {
    getSiteCfg();
    setProtoHTML();
    buildContainers();
});